package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"order_srv/cache"
	"order_srv/models"
	"order_srv/pkg"

	"order_srv/internal/svc"
	"order_srv/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderCreateLogic {
	return &OrderCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderCreateLogic) OrderCreate(in *order.OrderCreateRequest) (*order.OrderCreateResponse, error) {
	// todo: add your logic here and delete this line
	//用户是否存在
	var err error
	var u models.User
	u.ID = uint(in.UserId)
	if err = u.GetUserById(); err != nil {
		logx.Error("用户不存在")
		return nil, err
	}
	//商品是否存在
	var g models.Goods
	g.ID = uint(in.GoodsId)
	if err = g.Detail(); err != nil {
		logx.Error("商品不存在")
		return nil, err
	}
	//商品库存是否充足
	stock, _ := cache.GetGoodsStock(int(in.GoodsId))
	if stock < in.Num {
		logx.Error("商品库存不足")
		return nil, errors.New("商品库存不足")
	}
	//创建订单
	o := models.Order{
		UserId:  int(in.UserId),
		OrderSn: uuid.NewString(),
		Amount:  g.GoodsPrice * float64(in.Num),
	}
	if err = o.Create(); err != nil {
		logx.Error("订单创建失败")
		return nil, err
	}
	//创建订单商品
	var og models.OrderGoods
	og.GoodsPrice = g.GoodsPrice
	og.GoodsTitle = g.GoodsTitle
	og.GoodsId = int(g.ID)
	og.Num = int(in.Num)
	og.OrderId = int(o.ID)
	if err = og.Create(); err != nil {
		logx.Error("订单商品创建失败")
		return nil, err

	}
	pay := pkg.Alipay(o.OrderSn, fmt.Sprintf("%.2f", o.Amount))
	return &order.OrderCreateResponse{
		PayUrl: pay,
	}, nil
}
